package com.healthy.security.server;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Objects;

/**
 * TokenStoreUtil
 *
 * @author zhang.xiaoming
 */
@Component
public class TokenStoreUtil {

    private final TokenStore tokenStore;

    @Autowired
    public TokenStoreUtil(TokenStore tokenStore) {
        this.tokenStore = tokenStore;
    }

    /**
     * 移除redisTokenStore缓存的token信息
     */
    public void remove() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        if (Objects.nonNull(authentication) && authentication.getDetails() instanceof OAuth2AuthenticationDetails) {
            OAuth2AuthenticationDetails oAuth2AuthenticationDetails = (OAuth2AuthenticationDetails) authentication.getDetails();

            OAuth2AccessToken oAuth2AccessToken = tokenStore.readAccessToken(oAuth2AuthenticationDetails.getTokenValue());

            OAuth2RefreshToken oAuth2RefreshToken = oAuth2AccessToken.getRefreshToken();

            // 删除访问令牌
            tokenStore.removeAccessToken(oAuth2AccessToken);
            // 删除刷新令牌
            tokenStore.removeRefreshToken(oAuth2RefreshToken);
            // 通过刷新令牌删除访问令牌
            //tokenStore.removeAccessTokenUsingRefreshToken(oAuth2RefreshToken);
        }
    }

    public Map<String, Object> getAdditionalInformation() {
        Map<String, Object> information = null;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication.getDetails() instanceof OAuth2AuthenticationDetails) {
            OAuth2AuthenticationDetails oAuth2AuthenticationDetails = (OAuth2AuthenticationDetails) authentication.getDetails();
            OAuth2AccessToken oAuth2AccessToken = tokenStore.readAccessToken(oAuth2AuthenticationDetails.getTokenValue());
            if (Objects.nonNull(oAuth2AccessToken)) {
                information = oAuth2AccessToken.getAdditionalInformation();
            }
        }
        return information;
    }
}
